package com.srcbox.file.fragment

import android.content.pm.PackageInfo
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.srcbox.file.R
import com.srcbox.file.adapter.AppList
import com.srcbox.file.data.Search
import com.srcbox.file.util.EggUtil
import java.lang.NumberFormatException
import java.util.*

class AppFilesGet() : Fragment() {

    private var v: View? = null
    private var packList = java.util.ArrayList<PackageInfo?>()
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val v = inflater.inflate(R.layout.fragment_app_files_get, container, false)
        this.v = v
        initView()
        initEvent()
        return v
    }


    private fun initView() {
        val jsonO = EggUtil.readSetting(activity!!)
        val isHide = jsonO.getBoolean("os_is_cancel")
        val appList = v?.findViewById<RecyclerView>(R.id.app_re_list)
        packList =
            activity?.packageManager?.getInstalledPackages(0) as java.util.ArrayList<PackageInfo?>
        /*if (Build.VERSION.SDK_INT >= 24) {
            packList.sortWith(Comparator.comparingInt {
                try {
                    EggUtil.stringToAscii(
                        it?.applicationInfo?.loadLabel(activity!!.packageManager)?.toString()!!
                    )
                }catch (e:NumberFormatException){
                    0
                }
            })
        }*/
//        this.packList.sortedBy {}

        appList?.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        appList?.adapter = AppList(activity!!, packList, isHide)
        EggUtil.setViewRadius(
            v!!.findViewById<EditText>(R.id.app_search_edit),
            "#eeeeee",
            1,
            "#eeeeee",
            15f
        )

    }

    private fun initEvent() {

        v?.findViewById<TextView>(R.id.searchAppOn)?.setOnClickListener {
            Search.search(
                activity!!,
                v!!,
                packList,
                v!!.findViewById<EditText>(R.id.app_search_edit).text.toString()
            )
        }

        v?.findViewById<EditText>(R.id.app_search_edit)
            ?.setOnEditorActionListener { t, actionId, _ ->
                if (actionId == EditorInfo.IME_ACTION_NEXT) {
                    Search.search(activity!!, v!!, packList, t.text.toString())
                }
                true
            }
    }
}
